package com.authine.cloudpivot.ext.service;


import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeBasicRequest;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeOrganization;
import com.authine.cloudpivot.ext.dto.voucher.KingDeeBasicStats;
import com.authine.cloudpivot.ext.enums.kingdee.KingDeeBasicStatsEnum;
import com.authine.cloudpivot.ext.kingdee.work.KingDeeBasicStatsWork;
import com.authine.cloudpivot.ext.kingdee.work.OrganizationDataWork;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;


import java.util.List;


@Slf4j
public class KingDeeBasicStatsService {

    private KingDeeBasicStatsWork kingDeeBasicStatsWork = new KingDeeBasicStatsWork();
    private OrganizationDataWork organizationDataWork = new OrganizationDataWork();

    /**
     * 根据多个组织名称获取金蝶基础数据
     *
     * @return 金蝶基础数据列表
     */
    public SingleResponse<List<KingDeeBasicStats>> listByCompanyName(KingDeeBasicRequest request) {
        Assert.notNull(request, "根据多个组织名称获取金蝶基础数据 入参数据为空");

        return kingDeeBasicStatsWork.listByCompanyName(request);
    }


    /**
     * 保存金蝶基础数据
     *
     * @param params 金蝶基础数据实体
     * @return 保存成功的ID
     */
    public SingleResponse<List<String>> saveBatch(List<KingDeeBasicStats> params) {
        log.info("金蝶基础数据实体 start ##################");
        Assert.isTrue(!CollectionUtils.isEmpty(params), "保存金蝶基础数据 入参数据为空");

        for (KingDeeBasicStats param : params) {
            this.save(param);
        }

        log.info("金蝶基础数据实体 end  ##################");

        return SingleResponse.buildSuccess();
    }

    public String save(KingDeeBasicStats param) {

        Boolean checkResult = kingDeeBasicStatsWork.checkCodeAndNameExist(param.getKingdee_code(), param.getCompany_name(), param.getInfo_type());

        Assert.isTrue(!checkResult,"保存失败：" + param.getCompany_name() + " 名称 " + param.getKingdee_code() + " 编码在 " + param.getInfo_type() + "中已存在!");

        String id = kingDeeBasicStatsWork.save(param);
        log.info("金蝶基础数据实体 id:{}  ##################", id);

        KingDeeOrganization kingDeeOrganization = KingDeeOrganization.builder()
                .id(param.getKingdee_code())
                .companyName(param.getCompany_name())
                .vendorAndCustomer(param.getInfo_type().equals(KingDeeBasicStatsEnum.Customer))
                .build();

        organizationDataWork.createOrganization(kingDeeOrganization);

        return id;
    }

    /**
     * 修改金蝶基础数据
     *
     * @param param 金蝶基础数据实体
     * @return 修改结果提示信息
     */
    public SingleResponse<Integer> update(KingDeeBasicStats param) {
        Assert.notNull(param, "根据多个组织名称获取金蝶基础数据 入参数据为空");

        return kingDeeBasicStatsWork.update(param);
    }

}
